package com.et.u1.util;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
import java.util.Random;

/**
 * Created by AItsuki on 2016/1/12.
 */
public class BallView extends View {

    static class Ball {
        int radius; // 半径
        float cx;   // 圆心
        float cy;   // 圆心
        float vx; // X轴速度
        float vy; // Y轴速度
        Paint paint;

        // 移动
        void move() {
            //向角度的方向移动，偏移圆心
            cx += vx;
            cy += vy;
        }

        int left() {
            return (int) (cx - radius);
        }

        int right() {
            return (int) (cx + radius);
        }

        int bottom() {
            return (int) (cy + radius);
        }

        int top() {
            return (int) (cy - radius);
        }
    }


    public Ball mBalls;

    public BallView(Context context, AttributeSet attrs) {
        super(context, attrs);
        Random mRandom = new Random();
        mBalls = new Ball();
        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setColor(Color.BLUE);
        paint.setStyle(Paint.Style.FILL);
        paint.setAlpha(180);
        paint.setStrokeWidth(0);
        float speedX = 8;
        float speedY = 12.8f;
        mBalls.paint = paint;
        mBalls.vx = mRandom.nextBoolean() ? speedX : -speedX;
        mBalls.vy = mRandom.nextBoolean() ? speedY : -speedY;

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        // 初始化圆的半径和圆心
        mBalls.radius = 100;
        // 初始化圆心的位置
        mBalls.cx = 200;
        mBalls.cy = 200;
    }


    @Override
    protected void onDraw(Canvas canvas) {
        long startTime = System.currentTimeMillis();
        // 先画出圆
        canvas.drawCircle(mBalls.cx, mBalls.cy, mBalls.radius, mBalls.paint);
        // 球碰撞边界
        collisionDetectingAndChangeSpeed(mBalls); // 碰撞边界的计算
        mBalls.move(); // 移动
        long stopTime = System.currentTimeMillis();
        long runTime = stopTime - startTime;
        // 16毫秒执行一次
        postInvalidateDelayed(Math.abs(runTime - 16));
    }


    // 判断球是否碰撞碰撞边界
    public void collisionDetectingAndChangeSpeed(Ball ball) {
        int left = getLeft();
        int top = getTop();
        int right = getRight();
        int bottom = getBottom();

        float speedX = ball.vx;
        float speedY = ball.vy;

        // 碰撞左右，X的速度取反。 speed的判断是防止重复检测碰撞，然后黏在墙上了=。=
        if (ball.left() <= left && speedX < 0) {
            ball.vx = -ball.vx;
        } else if (ball.top() <= top && speedY < 0) {
            ball.vy = -ball.vy;
        } else if (ball.right() >= right && speedX > 0) {
            ball.vx = -ball.vx;
        } else if (ball.bottom() >= bottom && speedY > 0) {
            ball.vy = -ball.vy;
        }
    }

}